<!--
 * @Author: 黄宇/Hyuishine
 * @Date: 2022-05-24 14:20:30
 * @LastEditors: 黄宇/Hyuishine
 * @LastEditTime: 2024-09-27 10:16:25
 * @Description: 
 * @Email: hyuishine@gmail.com
 * @Company: 3xData
 * @youWant: add you want
-->
<template>
  <view class="container_page">
    <!-- 顶部自定义导航栏 -->
    <action-bar :options="navOptions" />

    <view class="main">
      <!-- 项目信息 -->

      <uni-section title="项目信息" type="line">
        <view class="formItem" @click="toSelectProject()">
          <view class="label">项目名称</view>
          <view class="content">
            {{ form.projectName }}
          </view>
        </view>
      </uni-section>

      <uni-section title="任务信息" type="line">
        <view class="formItem">
          <view class="label">任务名称</view>
          <input class="content" v-model="form.name" placeholder="请输入任务名称" />
        </view>

        <view class="formItem">
          <view class="label">任务类型</view>
          <picker mode="selector" class="content" :range="selector.type" :disabled="disabled" range-key="label"
            @change="typeChange($event, 'type')">
            <view :style="{ color: showForm.type ? '#333' : '#999' }">{{ showForm.type || '请选择任务类型' }}</view>
          </picker>
        </view>

        <view class="formItem">
          <view class="label">任务开始时间</view>
          <picker mode="date" class="content" :value="date" :disabled="disabled"
            @change="startChange($event, 'startDate')">
            <view :style="{ color: form.startDate ? '#333' : '#999' }">{{ form.startDate || '请选择任务开始时间' }}
            </view>
          </picker>
        </view>

        <view class="formItem">
          <view class="label">任务结束时间</view>
          <picker mode="date" class="content" :value="date" :start="pickerOptions.start" :disabled="disabled"
            @change="startChange($event, 'endDate')">
            <view :style="{ color: form.endDate ? '#333' : '#999' }">{{ form.endDate || '请选择任务结束时间' }}</view>
          </picker>
        </view>
        <view class="text-red tips">
          温馨提示：执业人员和项目负责人需在计划时间内完成任务，过期则不能执业和确认任务。
        </view>

        <view class="formItem" v-if="show3">
          <view class="label">年份</view>
          <view class="content">{{ form.year }}</view>
        </view>

        <view class="formItem" v-if="show1">
          <view class="label">月份</view>
          <view class="content">{{ form.month }}</view>
        </view>

        <view class="formItem" v-if="show2">
          <view class="label">季度</view>
          <view class="content">{{ form.quarter }}</view>
        </view>

        <view class="formItem" v-if="show4">
          <view class="label">其他</view>
          <input class="content" v-model="form.other" placeholder="请输入其他" />
        </view>

        <view class="formItem" @click="toSelectPeople">
          <view class="label">分配任务</view>
          <view class="content">
            <span style="color:red">
              {{ distributionState == '0' ? '未分配' : distributionState == '1' ? '未分配完成' : '已分配' }} </span>
          </view>
        </view>
      </uni-section>

      <uni-section title="备注" type="line">
        <view class="formItem">
          <input type="textarea" v-model="form.remark" placeholder="请输入备注信息" />
        </view>
      </uni-section>

      <view class="btn_processView" v-if="taskId" @click="viewProgress">查看进度</view>
      <view style="height: 100rpx"></view>
    </view>

    <view class="footer">
      <view class="btn btn_del" v-if="taskId" @click="deleteTask">删除任务</view>
      <view @click="submit" v-if="staffId == projectHead" class="btn btn_submit">提交</view>
    </view>
    <toast></toast>
  </view>
</template>
<script>
export default {
  data() {
    return {
      navOptions: {
        left: {
          icon: 'back'
        },
        center: {
          title: "任务详情"
        }
      },
      taskId: '',
      flag: false, // 修改标识
      form: {
        projectName: '',
        type: '',
        projectId: '',
        startDate: null,
        endDate: null,
        year: null,
        month: null,
        quarter: null,
        other: null,
        remark: null
      },
      disabledBox: false, // 提交时的防抖
      sign: true, // 人员分配
      show1: false, // 是否显示月度字段
      show2: false, // 是否显示季度字段
      show3: false, // 是否显示年度字段
      show4: false, // 是否显示其他字段
      // 下拉回显表单
      showForm: {},
      // 该字段代表分配任务状态, 当为0时，代表未分配，一个任务都没分配；当为1时，代表未分配完成，有任务未分配；当为2时，代表分配完成，全部任务都分配完成
      distributionState: 0,
      selector: {
        // 任务类型
        type: [{
          label: '月度',
          value: '1'
        },
        {
          label: '季度',
          value: '2'
        },
        {
          label: '年度',
          value: '3'
        },
        {
          label: '其他',
          value: '4'
        }],
      },
      disabled: false,

      // 结束日期 中的选择器的配置参数 
      pickerOptions: {
        start: '',
      },
      staffId: null, // 当前用户的staffId
      projectHead: null,
      loading: false,

      date: null,

    }
  },
  onLoad(options) {
    // 获取任务id
    if (options.id) {
      this.taskId = options.id
      this.disabled = options.disabled
      this.staffId = options.staffId
      this.flag = true
      this.getForm()
      this.getObtainLongitudeAnd()
    }
  },
  watch: {
    'form.type': {
      // 监听options，为标签初始化
      handler(val) {
        // 根据选择的任务类型 对相应的值进行带出
        this.toAssignTypeDate()

        // 字段联动
        if (val === '1') {
          this.show1 = true;
          this.show2 = false;
          this.show3 = true;
          this.show4 = false;
        } else if (val === '2') {
          this.show1 = false;
          this.show2 = true;
          this.show3 = true;
          this.show4 = false;
        } else if (val === '3') {
          this.show1 = false;
          this.show2 = false;
          this.show3 = true;
          this.show4 = false;
        } else if (val === '4') {
          this.show1 = false;
          this.show2 = false;
          this.show3 = false;
          this.show4 = true;
        } else {
          this.show1 = false;
          this.show2 = false;
          this.show3 = false;
          this.show4 = false;
        }

      },
      deep: true,
      immediate: true
    },
    // 监听维保列表
    'form.wbList': {
      handler(val) {
        if (val) {
          for (var i = 0; i < val.length; i++) {
            if (val[i].staffId.length > 0) {
              this.sign = false
              break
            }
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  destroyed() {
    //! 离开当前页面时，需要清空已分配人员信息，否则，在下一次分配人员时，之前分配的东西都回显回来了
    this.$store.state.task.taskData = []
  },
  methods: {
    // 校验
    validateForm() {
      let result = true
      if (this.form.projectName == null || this.form.projectName == '') {
        result = false
      } else if (this.form.name == null || this.form.name == '') {
        result = false
      } else if (this.form.startDate == null || this.form.startDate == '') {
        result = false
      } else if (this.form.endDate == null || this.form.endDate == '') {
        result = false
      } else if (this.showForm.type == null || this.showForm.type == '') {
        result = false
      }
      if (this.showForm.type == '月度' && (this.form.month == null || this.form.month == '' || this.form.year ==
        null || this.form.year == '')) {
        result = false
      }
      if (this.showForm.type == '季度' && (this.form.quarter == null || this.form.quarter == '' || this.form
        .year == null || this.form.year == '')) {
        result = false
      }
      if (this.showForm.type == '年度' && (this.form.year == null || this.form.year == '')) {
        result = false
      }
      if (this.showForm.type == '其他' && (this.form.other == null || this.form.other == '')) {
        result = false
      }
      if (this.distributionState != 2) {
        result = false
      }
      return result
    },
    // 获取项目负责人id和经纬度信息
    getObtainLongitudeAnd() {
      let dist = {
        taskId: this.taskId,
      };
      return new Promise((resolve, reject) => {
        this.$store.dispatch("ObtainLongitudeAndLatitude", dist).then((res) => {
          if (res && res.code === 200) {
            this.loginStaffId = res.data.loginStaffId;
            this.projectHead = res.data.projectHead
            resolve(res.data);
          } else {
            this.displayBox = true;
          }
        });
      });
    },
    // 提交
    submit() {
      if (this.disabledBox) {
        return
      }
      this.disabledBox = true
      if (this.anyError) {
        uni.hideLoading();
        this.$showToast({
          show: true,
          text: '任务开始时间只能选择同一个月内！'
        });
        return
      }
      //校验
      if (this.validateForm()) {

        if (this.loading) return

        this.loading = true

        if (this.taskId) {
          // 如果有任务id，则表示修改
          this.$store.dispatch('updateTask', this.form).then((res) => {
            if (res.code === 200) {
              this.$showToast({
                show: true,
                text: '保存成功'
              });
              uni.navigateBack({
                delta: 1
              })
            } else {
              uni.hideLoading();
              this.$showToast({
                show: true,
                text: res.msg
              });
              this.$store.state.task.taskData = []
              setTimeout(() => {
                this.disabledBox = false
              }, 1000);
            }
          }).finally(() => {
            let timer = setTimeout(() => {
              this.loading = false
              uni.hideLoading();
              clearTimeout(timer)
            }, 3000);
          })
        } else { // 新增
          this.$store.dispatch('addTask', this.form).then((res) => {
            if (res.code === 200) {
              this.$showToast({
                show: true,
                text: '保存成功'
              });
              this.$store.state.task.taskData = []
              uni.navigateBack({
                delta: 1
              })
            } else {
              this.$showToast({
                show: true,
                text: res.msg
              });
              this.$store.state.task.taskData = []
              setTimeout(() => {
                this.disabledBox = false
              }, 1000);
            }
          }).finally(() => {
            let timer = setTimeout(() => {
              this.loading = false
              uni.hideLoading();
              clearTimeout(timer)
            }, 3000);
          })
        }
      } else { // 返回错误信息
        this.$showToast({
          show: true,
          text: '信息未填写完整，请完善后再保存！'
        });
        setTimeout(() => {
          this.disabledBox = false
        }, 1000);
      }
    },
    // 任务时间change
    startChange(e, key) {
      const value = e.detail.value
      this.form[key] = value // 赋值

      // 当选择了 开始日期
      if (key === 'startDate') {
        // 为结束日期添加 能够选择的日期范围 的起点。
        this.pickerOptions.start = value

        // 开始日期选择了 则重置一次 结束日期
        this.form.endDate ? this.form.endDate = '' : null
      }
      if (key === 'endDate') {
        let starTime = this.form.startDate.slice(8, 11)
        let endTime = this.form.endDate.slice(8, 11)
        let sub = Number(endTime) - Number(starTime)
        if (sub >= 7) {
          this.$showToast({
            show: true,
            text: '任务分配时，开始时间和结束时间最大只能相隔7天！'
          });
          this.form.startDate = null
          this.form.endDate = null
          this.form.year = ''
          this.form.month = ''
          this.form.quarter = ''
          this.form.other = ''
          return
        }
      }

      // 根据选择的任务类型 对相应的值进行带出
      this.toAssignTypeDate()
    },

    // 给任务类型对应的值 带出，然后把其他的重置。
    toAssignTypeDate() {
      const lables = ['month', 'quarter', 'year', 'other']

      const typeToShow = [{ // 每种类型需要对其字段带出的
        type: '1',
        show: ['year', 'month']
      }, {
        type: '2',
        show: ['quarter', 'year']
      }, {
        type: '3',
        show: ['year']
      }, {
        type: '4',
        show: []
      },]

      if (this.form.type) {
        // 原始数据 即开始日期
        let originValue = this.form.startDate

        // 准备赋值的数据
        let valueToAssign = {
          year: '',
          month: '',
          quarter: '',
          other: ''
        }

        // 如果有数据 则算出对应的数据
        if (originValue) {
          let year = originValue.slice(0, 4) // 取出的年份
          let month = Number(originValue.slice(5, 7)) // 取出的月份
          let quarter = Math.ceil(month / 3) // 季度

          valueToAssign = {
            year: year,
            month: month,
            quarter: quarter,
            other: ''
          }
        }

        // 需要赋值的字段英文名
        let toAssign = typeToShow.find(item => item.type === this.form.type).show

        lables.forEach(item => {
          // 如果 需要赋值带出的字段中 有该字段 则为该字段赋值，否则 重置
          if (toAssign.findIndex(toAssignLabel => toAssignLabel === item) != -1) {
            this.form[item] = valueToAssign[item]
          } else {
            this.form[item] = ''
          }
        })
      } else {
        // 没有选类型 则全部置空
        lables.forEach(item => {
          this.form[item] = ''
        })
      }
    },
    deleteTask() {
      let that = this
      uni.showModal({
        title: '提示',
        content: '是否确认删除，删除了任务将不存在，若执业了，则该任务的执业数据将丢失',
        success: function (res) {
          if (res.confirm) {
            that.del()
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },

    // 删除任务
    del() {
      this.$store.dispatch('delTask', this.taskId).then(res => {
        if (res && res.code === 200) {
          this.$showToast({
            show: true,
            text: '删除成功'
          });
          uni.navigateBack({
            delete: 1
          })
        }
      })
    },
    // 查看进度
    viewProgress() {
      // 存任务id
      this.$store.state.unitTask.taskId = this.taskId
      // 跳转至对应页面
      uni.redirectTo({
        url: '../../pages_workTableChild/manage/CategoryGrade?loginStaffId=' + this.loginStaffId + "&design=confirm" + "&dontBtn=true"
      })
    },
    // 任务类型切换
    typeChange(e, label) {
      this.form[label] = this.selector[label][e.detail.value].value
      this.showForm[label] = this.selector[label][e.detail.value].label
    },

    // 时间change
    endChange(e, label) {
      this.form[label] = e.detail.value
    },
    // 获取表单
    getForm() {
      if (this.loading) return

      this.loading = true

      this.$store.dispatch('unitForm', this.taskId).then(res => {
        if (res && res.code === 200) {
          this.form = res.data
          if (this.form.type) {
            this.selector.type.forEach(element => {
              if (element.value === this.form.type) {
                this.showForm.type = element.label
              }
            });
          }
          this.$store.state.task.taskData = res.data.wbList
          this.distributionState = 2
        }
      }).finally(() => {
        let timer = setTimeout(() => {
          this.loading = false
          uni.hideLoading();
          clearTimeout(timer)
        }, 3000);
      })
    },
    // 跳往选择项目页面
    toSelectProject() {
      if (this.flag) {
        this.$showToast({
          show: true,
          text: '已提交的任务不允许修改关联项目'
        });
      } else {
        this.$nextTick(() => {
          this.distributionState = 0
          this.form.wbList = []
        })
        uni.navigateTo({
          // todo 携带参数
          url: './components/projectSelector'
        })
      }
    },
    // 跳往分配人员页面
    toSelectPeople() {
      if (this.form.projectId) {
        uni.navigateTo({
          // todo 携带参数
          url: './components/taskAssignment?projectId=' + this.form.projectId
        })
      } else {
        this.$showToast({
          show: true,
          text: '请先选择项目'
        });
      }
    },
    //! 提供给选择项目页面调取的 处理项目信息的方法
    getProjectInfo(projectInfo) {
      this.form.projectId = projectInfo.projectId
      this.form.projectName = projectInfo.name
    },
    //! 提供给选择执业人员页面调取的 处理执业人员信息的方法
    getWbList(wbList) {
      this.form.wbList = wbList
      for (let i = 0; i < wbList.length; i++) {
        if (wbList[i].staffId.length == 0) {
          this.distributionState = 1
          break;
        } else {
          this.distributionState = 2
        }
      }
    },
    onDateSelectorChange({ startDate, endDate }) {
      console.log('onDateSelectorChange', startDate, endDate);
    },
    onDateSelectorSubmit({ startDate, endDate }) {
      console.log('onDateSelectorSubmit', startDate, endDate);
    },
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

::v-deep .uni-section {
  margin-top: 0;
  background-color: transparent;
}

.container_page {
  min-height: 100vh;
  width: 100vw;

  .main {
    width: 100%;
    height: calc(100% - 80rpx);
    background: $OVERALL_SITUATION_BACKGROUND_GRADIENT;
  }

  .formItem {
    display: flex;
    align-items: center;
    padding-bottom: 25rpx;
    width: calc(100% - 40rpx);
    margin: 0 auto 24rpx;
    background-color: #fff;
    border-radius: 20rpx;
    min-height: 110rpx;
    padding: 0 24rpx;

    .label {
      color: #333;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 36rpx;
      width: 40%;
    }

    .required {
      &::before {
        content: "*";
        margin: 0 10rpx;
        color: #ea0707;
      }
    }

    .content {
      text-align: right;
      width: 60%;
      font-size: 28rpx
    }
  }

  .tips {
    width: calc(100% - 40rpx);
    margin: 0 auto 24rpx;
  }

  .btn_processView {
    height: 80rpx;
    width: calc(100% - 40rpx);
    background-color: rgba(52, 90, 199, 0.5);
    margin: 0 auto 24rpx;
    line-height: 80rpx;
    border-radius: 20rpx;
    text-align: center;
    color: #fff;
  }

  .footer {
    width: 100%;
    background-color: #fff;
    height: 100rpx;
    display: flex;
    position: fixed;
    bottom: 0;
    z-index: 9;
    align-items: center;
    border-top: 1rpx solid #e5e5e5;

    .btn {
      border-radius: 20rpx;
      text-align: center;
      font-size: 28rpx;
      line-height: 80rpx;
      height: 80rpx;
      margin: 10rpx 20rpx;
      flex: 1;
    }

    .btn_submit {
      background: $OVERALL_CONFIRM_BUTTON_COLOR;
      color: #fff
    }



    .btn_del {
      background: linear-gradient(90deg, #fc5151 0%, #ff2626 100%);
      color: #fff;
    }
  }
}
</style>
